using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using MediatR;
using RBAC.Domain.SalesManage;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.ERP.SalesManagement.Return;
using RBAC.Write.Api.Infrastructure;

namespace RBAC.Write.Api.Application.Handler.ERP.SalesManagement.Return
{
    /// <summary>
    /// 审核/反审核/退回 退货通知单处理器
    /// </summary>
    public class ApproveOrReturnReturnNoticeHandler : IRequestHandler<ApproveOrReturnReturnNoticeCommand, APIResult<bool>>
    {
        private readonly IDbConnectionFactory _dbConnectionFactory;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbConnectionFactory">数据库连接工厂</param>
        public ApproveOrReturnReturnNoticeHandler(IDbConnectionFactory dbConnectionFactory)
        {
            _dbConnectionFactory = dbConnectionFactory;
        }

        /// <summary>
        /// 处理审核/反审核/退回请求
        /// </summary>
        /// <param name="request">审核命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>处理结果</returns>
        public async Task<APIResult<bool>> Handle(ApproveOrReturnReturnNoticeCommand request, CancellationToken cancellationToken)
        {
            try
            {
                using var connection = _dbConnectionFactory.CreateConnection();

                // 1. 检查退货通知单是否存在
                var sqlCheck = @"SELECT BusinessStatus FROM ReturnNotice WHERE Id = @Id AND IsDeleted = 0";
                var currentStatus = await connection.ExecuteScalarAsync<int?>(sqlCheck, new { request.Id });

                if (!currentStatus.HasValue)
                {
                    return new APIResult<bool>
                    {
                        Code = APIEnums.Fail,
                        Msg = "退货通知单不存在"
                    };
                }

                int newStatus;
                string actionName;

                // 2. 根据操作类型设置新状态
                switch (request.Action)
                {
                    case 1: // 审核
                        if (currentStatus != 0) // 正常状态
                        {
                            return new APIResult<bool>
                            {
                                Code = APIEnums.Error,
                                Msg = "当前状态不能审核"
                            };
                        }
                        newStatus = 1; // 已审核状态
                        actionName = "审核";
                        break;

                    case 0: // 反审核
                        if (currentStatus != 1) // 已审核状态
                        {
                            return new APIResult<bool>
                            {
                                Code = APIEnums.Error,
                                Msg = "当前状态不能反审核"
                            };
                        }
                        newStatus = 0; // 正常状态
                        actionName = "反审核";
                        break;

                    case 2: // 退回
                        if (currentStatus != 0) // 正常状态
                        {
                            return new APIResult<bool>
                            {
                                Code = APIEnums.Error,
                                Msg = "当前状态不能退回"
                            };
                        }
                        newStatus = 2; // 已退回状态
                        actionName = "退回";
                        break;

                    default:
                        return new APIResult<bool>
                        {
                            Code = APIEnums.Error,
                            Msg = "无效的操作类型"
                        };
                }

                // 3. 更新退货通知单状态
                var sqlUpdate = @"
                    UPDATE ReturnNotice 
                    SET BusinessStatus = @NewStatus, 
                        UpdateTime = GETDATE(),
                        AuditUserId = @AuditUserId,
                        AuditTime = CASE WHEN @NewStatus = @ApprovedStatus THEN GETDATE() ELSE NULL END
                    WHERE Id = @Id";

                var affectedRows = await connection.ExecuteAsync(sqlUpdate, new
                {
                    NewStatus = newStatus,
                    ApprovedStatus = 1, // 已审核状态
                    AuditUserId = request.AuditUserId,
                    request.Id
                });

                if (affectedRows == 0)
                {
                    return new APIResult<bool>
                    {
                        Code = APIEnums.Error,
                        Msg = $"{actionName}失败"
                    };
                }

                return new APIResult<bool>
                {
                    Code = APIEnums.Success,
                    Msg = $"{actionName}成功",
                    Data = true
                };
            }
            catch (Exception ex)
            {
                return new APIResult<bool>
                {
                    Code = APIEnums.Error,
                    Msg = $"操作失败：{ex.Message}"
                };
            }
        }
    }
}